package com.abc.cloud.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.abc.cloud.common.exception.MyException;
import com.abc.cloud.common.utils.UserHolder;
import com.abc.cloud.dto.im.ContactsApplyResp;
import com.abc.cloud.entity.ContactsEntity;
import com.abc.cloud.service.*;
import com.abc.cloud.vo.im.ContactsApplyReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.abc.cloud.common.utils.PageUtil;
import com.abc.cloud.common.utils.Query;

import com.abc.cloud.dao.ContactsApplyDao;
import com.abc.cloud.entity.ContactsApplyEntity;
import org.springframework.transaction.annotation.Transactional;


@Service("contactsApplyService")
public class ContactsApplyServiceImpl extends ServiceImpl<ContactsApplyDao, ContactsApplyEntity> implements ContactsApplyService {

    @Autowired
    private NoticeService noticeService;

    @Autowired
    private ContactsService contactsService;

    @Autowired
    private ChatService chatService;


    @Override
    public PageUtil queryPage(Map<String, Object> params) {
        IPage<ContactsApplyEntity> page = this.page(
                new Query<ContactsApplyEntity>().getPage(params),
                new QueryWrapper<ContactsApplyEntity>()
        );

        return new PageUtil(page);
    }

    @Override
    public void saveContactsApply(ContactsApplyReq contactsApplyReq, Long userId, String username) {
        if (userId.equals(contactsApplyReq.getTargetId())){
            throw new MyException("不能申请自己为好友");
        }

        // 检查是否已经是好友
        ContactsEntity one = contactsService.getOne(new QueryWrapper<ContactsEntity>().eq("user_id", userId)
                .eq("contacts_id", contactsApplyReq.getTargetId()).eq("status", 1));
        if (one != null){
            throw new MyException("不能重复添加好友");
        }

        // 检查是否已经申请过了
        ContactsApplyEntity findApply = this.baseMapper.selectOne(new QueryWrapper<ContactsApplyEntity>().eq("target_id", contactsApplyReq.getTargetId())
                .eq("user_id", userId).eq("status", 1));
        if (findApply != null){
            throw new MyException("不能重复申请");
        }

        ContactsApplyEntity contactsApplyEntity = BeanUtil.copyProperties(contactsApplyReq, ContactsApplyEntity.class);
        contactsApplyEntity.setUserId(userId);
        contactsApplyEntity.setUsername(username);
        this.baseMapper.insert(contactsApplyEntity);
    }

    @Override
    public List<ContactsApplyResp> listApply() {
        Long userId = UserHolder.getUser().getId();
        List<Integer> statusList = new ArrayList<>();
        statusList.add(1);
        statusList.add(2);
        statusList.add(3);
        return this.baseMapper.queryList(userId, statusList);
    }

    @Transactional
    @Override
    public void examineById(Long userId, String username, Long id, Integer status, String note, Long groupId) {
        ContactsApplyEntity contactsApplyEntity = this.baseMapper.selectById(id);
        if (!contactsApplyEntity.getTargetId().equals(userId)){
            throw new MyException("身份验证出错");
        }

        contactsApplyEntity.setStatus(status);
        this.baseMapper.updateById(contactsApplyEntity);

        // 同意就添加联系人
        if (status == 2){
            contactsService.saveContacts(contactsApplyEntity.getUserId(), userId, contactsApplyEntity.getNote(), contactsApplyEntity.getGroupId());
            contactsService.saveContacts(userId, contactsApplyEntity.getUserId(), note, groupId);

            // 添加聊天
            chatService.saveOneChat(userId, contactsApplyEntity.getUserId());
        }

        // 同意或者拒绝就发送通知
        if (status == 2 || status == 3){
            // 发送系统通知给用户
            sendNotice(userId, username, contactsApplyEntity.getUserId(), contactsApplyEntity.getUsername(), contactsApplyEntity.getType(), status);
        }
    }

    @Override
    public void deleteAllOpContactsApply(Long userId, Integer status) {
        this.baseMapper.changeAllOpContactsApply(userId, status);
    }

    private void sendNotice(Long userId, String username, Long fromId, String fromUsername, Integer type, Integer status) {
        if (type == 1){
            if (status == 2){
                String content = "账号(" + username + ")同意了你的联系人请求";
                noticeService.sendNotice("联系人申请通过", content, userId, username, fromId, fromUsername, 2, 2);
            }
            else if (status == 3) {
                String content = "账号(" + username + ")拒绝了你的联系人请求";
                noticeService.sendNotice("联系人申请不通过", content, userId, username, fromId, fromUsername, 2, 2);
            }
            else throw new MyException("未知类型，请联系管理员");
        }
        else if(type == 2){
            if (status == 2) {
                String content = "群聊(" + userId + ")同意了你的群聊请求";
                noticeService.sendNotice("群聊申请通过", content, userId, username, fromId, fromUsername, 2, 2);
            }
            else if (status == 3) {
                String content = "群聊(" + userId + ")拒绝了你的群聊请求";
                noticeService.sendNotice("群聊申请不通过", content, userId, username, fromId, fromUsername,2, 2);
            }
            else throw new MyException("未知类型，请联系管理员");
        }
    }

}